package com.thinkcube.edutainment.fragment;

import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.thinkcube.edutainment.EdutainmentConstant;
import com.thinkcube.edutainment.R;
import com.thinkcube.edutainment.ReachabilityTest;
import com.thinkcube.edutainment.adapters.LessonContentAdapter;
import com.thinkcube.edutainment.client.CourseClient;
import com.thinkcube.edutainment.client.LessonClient;
import com.thinkcube.edutainment.client.UserClient;
import com.thinkcube.edutainment.domain.LessonContent;
import com.thinkcube.edutainment.domain.MetaData;
import com.thinkcube.edutainment.domain.OAuth;
import com.thinkcube.edutainment.domain.data.LessonContentData;
import com.thinkcube.edutainment.domain.data.LessonData;
import com.thinkcube.edutainment.domain.dto.CourseDto;
import com.thinkcube.edutainment.domain.dto.OAuthDto;
import com.thinkcube.edutainment.service.SPreferences_;

/**
 * A fragment representing a lesson content screen.
 * 
 */
@EFragment
public class FollowCoureseDetail extends Fragment implements
		OnItemClickListener {

	@ViewById(R.id.name)
	TextView name;

	@ViewById(R.id.list)
	ListView listView;

	@ViewById(R.id.progressBar)
	ProgressBar dialog;

	@ViewById(R.id.lesson_no)
	TextView lesssonNo;

	@FragmentArg("lessonContents")
	LessonData lessonItem;

	@ViewById(R.id.completed)
	TextView completed;

	@ViewById(R.id.mark_as_complete)
	Button markAsCompleted;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.follow_course_detail, container,
				false);
		if (getArguments().containsKey("lessonContents")) {

			lessonItem = getArguments().getParcelable("lessonContents");

			System.out.println("COMPLEDETD STATUS"
					+ lessonItem.getCompleteStatus());

		}
		return view;
	}

	@Bean
	OAuthDto oAuthDto;

	@RestService
	UserClient userClient;

	@RestService
	LessonClient lessonClient;

	@AfterViews
	void iniUi() {
		if (lessonItem != null) {

			name.setText(lessonItem.getLessonTitle());
			// lesssonNo.setText(lessonItem.getLessonCode() + "-");
			dialog.setVisibility(View.VISIBLE);
			gettoken(lessonItem);

			if ((lessonItem.getCompleteStatus() != null)) {
				if (lessonItem.getCompleteStatus().equals("true")) {
					markAsCompleted.setVisibility(View.GONE);
					completed.setVisibility(View.VISIBLE);
				}
			} else {
				// markAsCompleted.setVisibility(View.GONE);
				// completed.setVisibility(View.VISIBLE);
			}
		}
	}

	@Background
	void gettoken(final LessonData lessonData) {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					setTokenUi(lessonData, userClient.getRequestToken(oAuthDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});

	}

	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
	}

	@Bean
	CourseDto courseDto;

	String token;

	@Background
	void setTokenUi(LessonData lessonData, OAuth requestToken) {
		courseDto.setAuthToken(requestToken.getoAuth().getToken());
		token = requestToken.getoAuth().getToken();
		courseDto.setLessonId(lessonData.getLessonId());
		courseDto.setUserId(pref.getId().get());

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					doUi(lessonClient.getContent(courseDto.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});

	}

	@Bean
	LessonContentAdapter lessonContntItem;

	@ViewById(R.id.progressBar)
	ProgressBar progress;

	@Trace
	@UiThread
	void doUi(LessonContent lessonContent) {

		dialog.setVisibility(View.GONE);

		final List<LessonContentData> lessonContentList = lessonContent
				.getLessonContentDataList();
		if (lessonContent.getLessonContentDataList() != null) {
			lessonContntItem.setLessonContentDataList(lessonContentList);
			progress.setVisibility(View.GONE);
			listView.setAdapter(lessonContntItem);

			listView.setOnItemClickListener(this);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		Log.v("Lesson URL", lessonContntItem.getItem(position).getUrl());
		Log.v("MYME TYPE", lessonContntItem.getItem(position).getType());

		if (lessonContntItem.getItem(position).getIsSuppored().equals("true")
				&& lessonContntItem.getItem(position).getIsSuppored() != null) {

			if ((lessonContntItem.getItem(position).getType()
					.equals("presentation")
					|| (lessonContntItem.getItem(position).getType()
							.equals("pdf")) || (lessonContntItem.getItem(
					position).getType().equals("msword")))) {

				displayDocumentLessons(lessonContntItem.getItem(position)
						.getUrl());

			} else if (lessonContntItem.getItem(position).getType()
					.equals("image")) {

				// String imagePath=lessonContntItem.getItem(position).getUrl();
				FragmentTransaction fragmentTransaction = getFragmentManager()
						.beginTransaction();
				fragmentTransaction.replace(
						R.id.lesson_content,
						ImageViewFragment.newInstance(lessonContntItem.getItem(
								position).getUrl()));
				fragmentTransaction.commit();

			} else if ((lessonContntItem.getItem(position).getType()
					.equals("video"))
					|| (lessonContntItem.getItem(position).getType()
							.equals("audio"))
					|| ((lessonContntItem.getItem(position).getType()
							.equals("vlink")))) {

				displayVideoLessons(
						lessonContntItem.getItem(position).getUrl(),
						lessonContntItem.getItem(position).getTitle());

			} else if ((lessonContntItem.getItem(position).getType()
					.equals("link"))) {
				displayUrlLessons(lessonContntItem.getItem(position).getUrl());
			} else if ((lessonContntItem.getItem(position).getType()
					.equals("text"))) {
				displayHtmlLessons(lessonContntItem.getItem(position)
						.getDescription());

			}
		} else {
			showMessge("This content not support");
		}

	}

	@Pref
	SPreferences_ pref;

	@RestService
	CourseClient courseClient;

	@Trace
	@Background
	void marckascomleted() {
		courseDto.setAuthToken(token);

		courseDto.setUserId(pref.getId().get());

		courseDto.setLessonId(lessonItem.getLessonId());

		courseDto.setStatus("1");

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					markascompletdResult(courseClient.markascompleted(courseDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});
	}

	@UiThread
	void markascompletdResult(MetaData markascompleted) {

		showMessge(markascompleted.getMessageText());
	}

	void displayDocumentLessons(String url) {
		/* document type */
		FragmentTransaction fragmentTransaction = getFragmentManager()
				.beginTransaction();
		Bundle bundle = new Bundle();
		bundle.putString("Url", url);
		DocumentViewrFragment document = new DocumentViewrFragment();
		document.setArguments(bundle);
		fragmentTransaction.replace(R.id.lesson_content, document);
		fragmentTransaction.addToBackStack(null);

		fragmentTransaction.commit();
	}

	void displayVideoLessons(String url, String title) {

		FragmentTransaction fragmentTransaction = getFragmentManager()
				.beginTransaction();
		Bundle bundle = new Bundle();
		bundle.putString("Url", url);
		bundle.putString("title", title);
		VideoFragment videoLessons = new VideoFragment_();
		videoLessons.setArguments(bundle);
		fragmentTransaction.replace(R.id.lesson_content, videoLessons);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();
	}

	void displayUrlLessons(String Url) {
		FragmentTransaction fragmentTransaction = getFragmentManager()
				.beginTransaction();
		System.out.println("URL >>>>>" + Url);

		Bundle bundle = new Bundle();
		bundle.putString("Url", Url);

		HtmlFragment htmlLessons = new HtmlFragment_();
		htmlLessons.setArguments(bundle);

		fragmentTransaction.replace(R.id.lesson_content, htmlLessons);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();

	}

	void displayHtmlLessons(String content) {

		FragmentTransaction fragmentTransaction = getFragmentManager()
				.beginTransaction();

		Bundle bundle = new Bundle();

		bundle.putString("content", content);
		HtmlFragment htmlLessons = new HtmlFragment_();
		htmlLessons.setArguments(bundle);

		fragmentTransaction.replace(R.id.lesson_content, htmlLessons);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();

	}

	@Click({ R.id.mark_as_complete })
	void onClick(View veiw) {
		switch (veiw.getId()) {
		case R.id.mark_as_complete:
			marckascomleted();
			break;

		default:
			break;
		}
	}
}
